#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python_learning 
@File ：socket_client_with_GUI_chat8.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2024/3/1 17:23 
"""

import socket
import tkinter as tk
from threading import Thread


class SocketServer:
    def __init__(self, port):
        self.port = port
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.bind(("0.0.0.0", self.port))
        self.server_socket.listen(1)
        self.client_socket, self.client_address = self.server_socket.accept()

    def receive_messages(self, text_widget):
        while True:
            data = self.client_socket.recv(1024)
            if not data:
                break
            message = data.decode("utf-8")
            text_widget.insert(tk.END, f"Received: {message}\n")
            text_widget.see(tk.END)

    def close_socket(self):
        self.client_socket.close()
        self.server_socket.close()


class App:
    def __init__(self, root):
        self.root = root
        self.root.title("Socket Message Receiver")

        # 创建监听端口配置框
        self.port_label = tk.Label(root, text="Listen Port:")
        self.port_label.grid(row=0, column=0, padx=5, pady=5)
        self.port_entry = tk.Entry(root)
        self.port_entry.insert(0, "8888")  # 默认监听端口为8888
        self.port_entry.grid(row=0, column=1, padx=5, pady=5)

        # 创建配置确认按钮
        self.config_button = tk.Button(
            root, text="Start Listening", command=self.start_listening
        )
        self.config_button.grid(row=0, column=2, padx=5, pady=5)

        # 创建监听结果显示区域
        self.result_text = tk.Text(root, height=10, width=50)
        self.result_text.grid(row=1, column=0, columnspan=3, padx=5, pady=5)

        # 创建清空结果输出按钮
        self.clear_button = tk.Button(
            root, text="Clear Results", command=self.clear_results
        )
        self.clear_button.grid(row=2, column=0, columnspan=3, padx=5, pady=5)

        # 创建SocketServer实例
        self.socket_server = None

    def start_listening(self):
        port = int(self.port_entry.get())
        self.socket_server = SocketServer(port)

        # 启动新线程用于接收消息
        receive_thread = Thread(
            target=self.socket_server.receive_messages, args=(self.result_text,)
        )
        receive_thread.start()

    def clear_results(self):
        self.result_text.delete(1.0, tk.END)

    def close_socket(self):
        if self.socket_server:
            self.socket_server.close_socket()


root = tk.Tk()
app = App(root)
root.mainloop()
